/**
 * 服务器管理服务类
 * 负责服务器列表管理、状态监控、连接测试等核心业务逻辑
 * 
 * @author mixed-project
 * @version 1.0
 * @since 2024
 */
package com.mixed.mixedserver.service;

import com.mixed.mixedserver.game.network.GameNettyServer;
import com.mixed.mixedserver.game.network.GameServerHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ServerService {
    
    @Autowired
    private GameNettyServer gameNettyServer;
    
    @Autowired
    private GameServerHandler gameServerHandler;
    
    @Value("${server.port:8080}")
    private int httpPort;
    
    @Value("${netty.server.port:9999}")
    private int nettyPort;
    
    // 模拟的服务器列表缓存
    private final Map<String, Map<String, Object>> serverCache = new ConcurrentHashMap<>();
    
    // 服务器统计数据
    private final Map<String, Object> serverStats = new ConcurrentHashMap<>();
    
    /**
     * 获取可用服务器列表
     * 
     * @return 服务器列表
     */
    public List<Map<String, Object>> getAvailableServers() {
        // 初始化服务器列表（实际项目中可能从数据库或配置文件读取）
        initializeServerList();
        
        List<Map<String, Object>> serverList = new ArrayList<>();
        
        // 添加当前服务器
        Map<String, Object> currentServer = getCurrentServerInfo();
        serverList.add(currentServer);
        
        // 添加其他模拟服务器
        serverList.addAll(serverCache.values());
        
        return serverList;
    }
    
    /**
     * 获取指定服务器信息
     * 
     * @param serverId 服务器ID
     * @return 服务器信息
     */
    public Map<String, Object> getServerInfo(String serverId) {
        if ("current".equals(serverId) || "server-1".equals(serverId)) {
            return getCurrentServerInfo();
        }
        return serverCache.get(serverId);
    }
    
    /**
     * 获取当前服务器状态
     * 
     * @return 当前服务器状态
     */
    public Map<String, Object> getCurrentServerStatus() {
        Map<String, Object> status = new HashMap<>();
        
        boolean isRunning = gameNettyServer.isRunning();
        int onlineCount = gameServerHandler.getOnlinePlayerCount();
        
        status.put("serverId", "server-1");
        status.put("name", "主服务器");
        status.put("status", isRunning ? "online" : "offline");
        status.put("currentPlayers", onlineCount);
        status.put("maxPlayers", 100);
        status.put("playerPercentage", Math.round((onlineCount / 100.0) * 100));
        status.put("ping", isRunning ? new Random().nextInt(50) + 10 : -1);
        status.put("region", "亚洲");
        status.put("gameMode", "经典模式");
        status.put("version", "1.0.0");
        status.put("uptime", getServerUptime());
        status.put("lastUpdate", System.currentTimeMillis());
        
        return status;
    }
    
    /**
     * 刷新服务器列表
     */
    public void refreshServerList() {
        // 清除缓存
        serverCache.clear();
        
        // 重新初始化
        initializeServerList();
        
        // 更新统计信息
        updateServerStatistics();
    }
    
    /**
     * 测试服务器连接
     * 
     * @param serverId 服务器ID
     * @return 连接测试结果
     */
    public Map<String, Object> pingServer(String serverId) {
        Map<String, Object> result = new HashMap<>();
        
        if ("current".equals(serverId) || "server-1".equals(serverId)) {
            // 测试当前服务器
            boolean isRunning = gameNettyServer.isRunning();
            result.put("serverId", serverId);
            result.put("reachable", isRunning);
            result.put("ping", isRunning ? new Random().nextInt(30) + 5 : -1);
            result.put("timestamp", System.currentTimeMillis());
        } else {
            // 测试其他服务器（模拟）
            Map<String, Object> serverInfo = serverCache.get(serverId);
            if (serverInfo != null) {
                String status = (String) serverInfo.get("status");
                boolean reachable = "online".equals(status);
                result.put("serverId", serverId);
                result.put("reachable", reachable);
                result.put("ping", reachable ? new Random().nextInt(100) + 20 : -1);
                result.put("timestamp", System.currentTimeMillis());
            } else {
                result.put("serverId", serverId);
                result.put("reachable", false);
                result.put("ping", -1);
                result.put("error", "服务器不存在");
                result.put("timestamp", System.currentTimeMillis());
            }
        }
        
        return result;
    }
    
    /**
     * 获取服务器统计信息
     * 
     * @return 统计信息
     */
    public Map<String, Object> getServerStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        stats.put("totalServers", serverCache.size() + 1); // +1 for current server
        stats.put("onlineServers", getOnlineServerCount());
        stats.put("totalPlayers", getTotalPlayerCount());
        stats.put("averagePing", getAveragePing());
        stats.put("serverLoad", getServerLoad());
        stats.put("lastRefresh", serverStats.getOrDefault("lastRefresh", System.currentTimeMillis()));
        
        return stats;
    }
    
    /**
     * 初始化服务器列表
     */
    private void initializeServerList() {
        if (serverCache.isEmpty()) {
            // 模拟其他服务器数据
            createMockServer("server-2", "备用服务器", "online", 45, 100, "欧洲");
            createMockServer("server-3", "测试服务器", "maintenance", 0, 50, "北美");
            createMockServer("server-4", "高级服务器", "online", 78, 150, "亚洲");
            createMockServer("server-5", "新手服务器", "offline", 0, 80, "亚洲");
        }
    }
    
    /**
     * 创建模拟服务器数据
     */
    private void createMockServer(String id, String name, String status, int currentPlayers, int maxPlayers, String region) {
        Map<String, Object> server = new HashMap<>();
        server.put("serverId", id);
        server.put("name", name);
        server.put("status", status);
        server.put("currentPlayers", currentPlayers);
        server.put("maxPlayers", maxPlayers);
        server.put("playerPercentage", Math.round((currentPlayers / (double) maxPlayers) * 100));
        server.put("ping", "online".equals(status) ? new Random().nextInt(80) + 20 : -1);
        server.put("region", region);
        server.put("gameMode", "经典模式");
        server.put("version", "1.0.0");
        server.put("host", "localhost");
        server.put("port", nettyPort + Integer.parseInt(id.substring(id.length() - 1)) - 1);
        server.put("lastUpdate", System.currentTimeMillis());
        
        serverCache.put(id, server);
    }
    
    /**
     * 获取当前服务器信息
     */
    private Map<String, Object> getCurrentServerInfo() {
        Map<String, Object> server = new HashMap<>();
        
        boolean isRunning = gameNettyServer.isRunning();
        int onlineCount = gameServerHandler.getOnlinePlayerCount();
        
        server.put("serverId", "server-1");
        server.put("name", "主服务器");
        server.put("status", isRunning ? "online" : "offline");
        server.put("currentPlayers", onlineCount);
        server.put("maxPlayers", 100);
        server.put("playerPercentage", Math.round((onlineCount / 100.0) * 100));
        server.put("ping", isRunning ? new Random().nextInt(30) + 5 : -1);
        server.put("region", "亚洲");
        server.put("gameMode", "经典模式");
        server.put("version", "1.0.0");
        server.put("host", "localhost");
        server.put("port", nettyPort);
        server.put("lastUpdate", System.currentTimeMillis());
        
        return server;
    }
    
    /**
     * 获取在线服务器数量
     */
    private long getOnlineServerCount() {
        long onlineCount = serverCache.values().stream()
            .mapToLong(server -> "online".equals(server.get("status")) ? 1 : 0)
            .sum();
        
        // 加上当前服务器
        if (gameNettyServer.isRunning()) {
            onlineCount++;
        }
        
        return onlineCount;
    }
    
    /**
     * 获取总玩家数量
     */
    private int getTotalPlayerCount() {
        int totalPlayers = serverCache.values().stream()
            .mapToInt(server -> (Integer) server.getOrDefault("currentPlayers", 0))
            .sum();
        
        // 加上当前服务器玩家数
        totalPlayers += gameServerHandler.getOnlinePlayerCount();
        
        return totalPlayers;
    }
    
    /**
     * 获取平均延迟
     */
    private double getAveragePing() {
        List<Integer> pings = new ArrayList<>();
        
        // 收集所有在线服务器的延迟
        serverCache.values().forEach(server -> {
            if ("online".equals(server.get("status"))) {
                pings.add((Integer) server.getOrDefault("ping", 0));
            }
        });
        
        // 加上当前服务器延迟
        if (gameNettyServer.isRunning()) {
            pings.add(new Random().nextInt(30) + 5);
        }
        
        return pings.stream().mapToInt(Integer::intValue).average().orElse(0.0);
    }
    
    /**
     * 获取服务器负载
     */
    private double getServerLoad() {
        // 简单的负载计算：基于当前玩家数和最大玩家数
        int currentPlayers = gameServerHandler.getOnlinePlayerCount();
        int maxPlayers = 100;
        return (currentPlayers / (double) maxPlayers) * 100;
    }
    
    /**
     * 获取服务器运行时间
     */
    private String getServerUptime() {
        // 简化的运行时间计算
        long uptimeMs = System.currentTimeMillis() - (System.currentTimeMillis() % (24 * 60 * 60 * 1000));
        long hours = uptimeMs / (60 * 60 * 1000);
        return hours + "小时";
    }
    
    /**
     * 更新服务器统计信息
     */
    private void updateServerStatistics() {
        serverStats.put("lastRefresh", System.currentTimeMillis());
        serverStats.put("totalRefreshCount", 
            (Integer) serverStats.getOrDefault("totalRefreshCount", 0) + 1);
    }
}